package com.appengine.hotornot.ui.controller;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.appengine.hotornot.service.AbstractService;
import com.appengine.hotornot.ui.model.CandidateModel;
import com.appengine.hotornot.utils.Config;

/**
 * Abstract UI controller
 * @author Aliaksandr_Spichakou
 *
 */
public abstract class AbstractUIController extends AbstractService{

	/**
	 * 
	 */
	private static final long serialVersionUID = -7143127175706662211L;
	protected HttpServletRequest request;
	public AbstractUIController(HttpServletRequest request){
		this.request = request;
	}
	
	/**
	 * Get input stream
	 * 
	 * @param feed2Update
	 * @return
	 * @throws Exception
	 */
	protected InputStream getInputStream()
			throws Exception {
		
		final Config cfg = Config.getInstance();
		final String spec = cfg.getAlbumURL();
		final URL url = new URL(spec);
		final HttpURLConnection connection = (HttpURLConnection) url
				.openConnection();

		connection.connect();

		final InputStream inputStream = connection.getInputStream();		
		return inputStream;
	}
	
	/**
	 * Create candidate
	 * @param photo
	 * @return
	 */
	protected CandidateModel createCandidate(Node item)
	{
		final CandidateModel candidate = new CandidateModel();
		
		final NodeList childNodes = item.getChildNodes();
		final int childLength = childNodes.getLength();
		for(int k=0;k<childLength;k++)
		{
			final Node pLink = childNodes.item(k);
			final String nodeName = pLink.getNodeName();
			if("id".equalsIgnoreCase(nodeName))
			{
				candidate.setPhotoId(pLink.getFirstChild().getNodeValue());
			}
			if("content".equalsIgnoreCase(nodeName))
			{
				final NamedNodeMap attributes = pLink.getAttributes();
				final Node namedItem = attributes.getNamedItem("src");
				candidate.setUrl(namedItem.getTextContent());
			}
			if("link".equalsIgnoreCase(nodeName))
			{
				final NamedNodeMap attributes = pLink.getAttributes();
				final Node namedItem = attributes.getNamedItem("rel");
				
				if(namedItem!=null && "alternate".equalsIgnoreCase(namedItem.getTextContent()))
				{
					final Node href = attributes.getNamedItem("href");
					candidate.setLink(href.getTextContent());
				}				
			}
			
		}				
		return candidate;
	}
	
	public abstract void doJob(); 
	
}
